<template>
	<view>
		<view class="item">
			<view class="title">大门</view>
			<view class="items" style="margin-left: 20rpx;">
				<image src="../../static/images/roomSetTins.png" mode=""></image>
				<text>门锁</text>
				<view class="kongzhi">
					<view @click="openBig()">开</view>
				</view>
			</view>
		</view>
		<view class="item" v-for="(item,index) in roomList" :key="item.id">
			<view class="title">{{item.name}}</view>
			<view class="box">
				<view class="items" v-if="item.lock_no != '0'">
					<image src="../../static/images/mensuo.png" mode=""></image>
					<text>门锁</text>
					<view class="kongzhi">
						<view @click="openRoomLock(item)">开</view>
					</view>
				</view>
				<view class="items" v-if="item.charge_id != '0'">
					<image src="../../static/images/chazuo.png" mode=""></image>
					<text>插座</text>
					<view class="kongzhi">
						<view @click="openChazuo(item)">开</view>
						<view @click="closeChazuo(item)">关</view>
					</view>
				</view>
				<!-- <view class="items" v-if="item.air_charge_id != '0'">
					<image src="../../static/images/kongtiao.png" mode=""></image>
					<text>空调空开</text>
					<view class="kongzhi">
						<view @click="openKongtiao(item.air_charge_id)">开</view>
						<view @click="closeKongtiao(item.air_charge_id)">关</view>
					</view>
				</view>
				<view class="items" v-if="item.lamp_charge_id != '0'">
					<image src="../../static/images/Frame.png" mode=""></image>
					<text>灯光</text>
					<view class="kongzhi">
						<view @click="openDong(item.lamp_charge_id)">开</view>
						<view @click="closeDong(item.lamp_charge_id)">关</view>
					</view>
				</view> -->
			</view>
		</view>
	</view>
</template>

<script>
	import { mapGetters } from 'vuex'
	export default {
		data() {
			return {
				pages: 1,
				// storeId: uni.getStorageSync('storeListId')[0],
				last_page: null,
				roomList: [],
				mobile: uni.getStorageSync('userinfo').mobile,
				// 锁的id
				lockId: '',
				blueYaCode: '',
				deviceId: '',
				servicesUUID: '',
				// 蓝牙延迟开锁
				delayTime: 300,
				notifyCharacteristicId: '',
				writeCharacteristicId: '',
				characteristics: [],
				isNotifyReturn: false,
				lock_brand: true, //锁的类型标记判断是不是231型号的锁
				maxFailNums: 3,
				failNums: 0,
			}
		},
		computed: {
			...mapGetters(['activeStore'])
		},

		onLoad() {
			this.getRoomList();
		},
		onReachBottom() {
			if (this.pages < this.last_page) {
				this.pages += 1;
				this.getRoomList();
			}
		},
		methods: {
			getRoomList() {
				const { activeStore: { id } } = this
				if (id === -1) {
					wx.showToast({
						title: '您没有选择店铺',
						duration: 2000,
						icon: 'error'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 2000)
					return
				}
				this.https('/room/lists', {
					store_id: id,
					page: this.pages
				}).then(res => {
					res.data.data.sort((a, b) => {
						return a.id * 1 - b.id * 1
					})
					if (this.pages == 1) {
						this.roomList = res.data.data;
					} else {
						this.roomList = this.roomList.concat(res.data.data);
					}
					this.last_page = res.data.last_page;
				}).catch(err => {
					uni.showToast({
						title: err.msg,
						icon: 'none'
					})
				})
			},
			// 开房间门锁
			openRoomLock(item) {
				let self = this;
				const { activeStore: { id } } = this
				uni.showLoading({
					mask: true,
					title: '正在尝试开锁....'
				})
				this.https('/lock/open', {
					type: 2,
					storeId: id,
					roomId: item.id,
					userId: uni.getStorageSync('userinfo').id,
					mobile: this.mobile
				}, "GET").then(res => {
					console.log('then');
					uni.hideLoading()
					const { code, msg } = res
					uni.showToast({
						title: msg,
						icon: 'none',
						duration: 2000,
					})
					this.blueYaCode = res.data.key
					this.lockId = res.data.lockId
					// 
					if (res.code == 2) {
						setTimeout(() => {
							if (this.blueYaCode) {
								// 初始化蓝牙判断是否开启蓝牙
								wx.openBluetoothAdapter({
									success(res) {
										// 执行搜索蓝牙
										setTimeout(() => {
												self.findBlue();
											},
											// 安卓开启蓝牙后，需要300ms延迟
											self.isModel() == 'android' ? self.delayTime : 0
										)
									},
									fail(err) {
										wx.showToast({
											title: '请开启蓝牙,部分安卓手机需要开启定位服务',
											icon: 'none',
											duration: 800
										})
										return
									}
								})
							}
						}, 1000)
					}

				}).catch(err => {
					console.log(err, 'eror');
					uni.showToast({
						title: err.msg,
						icon: 'none'
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			openBig() {
				const { activeStore: { id } } = this
				let self = this;
				uni.showLoading({
					mask: true,
					title: '正在尝试开锁....'
				})
				this.https('/lock/open', {
					type: 1,
					storeId: id,
					userId: uni.getStorageSync('userinfo').id,
					mobile: this.mobile
				}, "GET").then(res => {
					uni.hideLoading()
					this.blueYaCode = res.data.key
					this.lockId = res.data.lockId
					if (res.code == 2) {
						setTimeout(() => {
							if (this.blueYaCode) {
								// 初始化蓝牙判断是否开启蓝牙
								wx.openBluetoothAdapter({
									success(res) {
										// 执行搜索蓝牙
										setTimeout(() => {
												self.findBlue();
											},
											// 安卓开启蓝牙后，需要300ms延迟
											self.isModel() == 'android' ? self.delayTime : 0
										)
									},
									fail(err) {
										wx.showToast({
											title: '请开启蓝牙,部分安卓手机需要开启定位服务',
											icon: 'none',
											duration: 800
										})
										return
									}
								})
							}
						}, 1000)
					}
				}).catch(err => {
					uni.showToast({
						title: err.msg,
						icon: 'none'
					})
				})
			},
			// 开始搜索蓝牙
			findBlue() {
				let self = this
				wx.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: false,
					interval: 0,
					success(res) {
						setTimeout(() => {
							// 获取蓝牙列表
							self.getBlueYaList();
						}, 2000)
						wx.showLoading({
							title: '正在搜索设备',
						})
					},
					fail(res) {
						this.bluetoothFailAgain()
					},
				})
			},
			// 获取蓝牙列表
			getBlueYaList() {
				let self = this
				wx.getBluetoothDevices({
					success: function(res) {
						wx.hideLoading();
						self.findDevice(res.devices)
					}
				})
			},
			// 转换
			ab2hex(buffer) {
				var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function(bit) {
					return ('00' + bit.toString(16)).slice(-2);
				});
				return hexArr.join('');
			},
			//字符串转arrbuffer
			stringToHexBuffer(value) {
				var typedArray = new Uint8Array(value.match(/[\da-f]{2}/gi).map(function(h) {
					console.log('转数据1');
					return parseInt(h, 16);
				}))
				console.log('转数据2');
				return typedArray.buffer;
			},
			findDevice(devices) {
				let self = this

				function stringToHex(str) {
					const arr = str.split('.')
					return arr
						.map((item) => {
							let num = Number(item).toString(16)
							if (num.length < 2) {
								num = '0' + num
							}
							return num
						})
						.join('')
				}
				devices.forEach((device) => {
					// 蓝牙设备advertisData属性转换出来的数据
					var we = self.ab2hex(device.advertisData);
					// 锁设备的编号转换出来的数据
					var lockHexId = stringToHex(self.lockId);
					console.log(lockHexId === we, "判断");
					// 蓝牙设备advertisData属性转换出来的数据和锁设备的编号转换出来的数据相等则开门
					if (device.advertisData && self.ab2hex(device.advertisData) === lockHexId) {
						// self.setData({
						// 	deviceId: device.deviceId
						// })
						this.deviceId = device.deviceId
						self.connectBlueYa(device.deviceId);
					}
				})
			},
			// 开大门门锁(网络开锁)
			openBigDoor() {
				const { activeStore: { id } } = this
				this.https('/lock/open', {
					type: 1,
					storeId: id,
					userId: uni.getStorageSync('userinfo').id,
					mobile: this.mobile
				}, "GET").then(res => {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}).catch(err => {
					uni.showToast({
						title: err.msg,
						icon: 'none'
					})
				})
			},
			/*连接蓝牙 */
			connectBlueYa(deviceId) {
				let self = this
				wx.createBLEConnection({
					deviceId: deviceId,
					success(res) {
						console.log(res, "连接状态");
						if (res.errCode == 0) {
							wx.showToast({
								title: '蓝牙连接成功',
								icon: 'none',
								duration: 800
							})
							// 获取服务
							self.getBLEDeviceServices(deviceId)
						} else {
							wx.showToast({
								title: '蓝牙连接失败',
								icon: 'none',
								duration: 800
							})
						}
						// 关闭搜索功能
						wx.stopBluetoothDevicesDiscovery({
							success: function(res) {
								console.log("成功关闭蓝牙搜索功能");
							}
						})
					}
				})
			},
			// 获取服务UUID
			getBLEDeviceServices(deviceId) {
				let that = this
				wx.getBLEDeviceServices({
					deviceId,
					success: (res) => {
						console.log('getBLEDeviceServices', res)
						for (var i = 0; i < res.services.length; i++) {
							if (res.services[i].uuid == "0000FFF0-0000-1000-8000-00805F9B34FB") {
								this.servicesUUID = res.services[i].uuid
							}
						}
						// 获取连接设备具有读写功能服务的所有特征值
						that.getBLEDeviceCharacteristics();
					},
					fail: (res) => {
						console.log('getBLEDeviceServices fail', res);
						that.bluetoothFailAgain();
					}
				})
			},
			// 获取连接设备具有读写功能服务的所有特征值
			getBLEDeviceCharacteristics() {
				var that = this;
				wx.getBLEDeviceCharacteristics({
					deviceId: that.deviceId,
					serviceId: that.servicesUUID,
					success: (res) => {
						console.log(res.characteristics, "数据");
						//获取特征值
						for (var i = 0; i < res.characteristics.length; i++) {
							//把特征值id输出到控制台
							if (res.characteristics[i].properties.notify) {
								console.log("开启notify的characteristicId:" + res.characteristics[i].uuid);
								// that.setData({
								// 	notifyCharacteristicId: res.characteristics[i].uuid
								// })
								that.notifyCharacteristicId = res.characteristics[i].uuid
							}
							//res.characteristics[i].properties.write   
							if (res.characteristics[i].properties.write) {
								console.log("开启write的characteristicId:" + res.characteristics[i].uuid);
								// that.setData({
								// 	writeCharacteristicId: res.characteristics[i].uuid
								// })
								that.writeCharacteristicId = res.characteristics[i].uuid
							}
							if (res.characteristics[i].properties.read) {
								console.log("开启read的characteristicId:" + res.characteristics[i].uuid);
							}
						}
						console.log(that.writeCharacteristicId, "写入特征值ID");
						console.log(that.notifyCharacteristicId, "开启notify的ID");
						// 把数据写道data中
						// that.setData({
						// 	characteristics: res.characteristics
						// })
						that.characteristics = res.characteristics
						// 启用蓝牙特征值变化
						that.notifyBLECharacteristicValueChange();
					},
					fail: (res) => {
						console.log("失败了")
						this.bluetoothFailAgain();
					},
					complete: (res) => {

					},
				})
			},
			// 监听蓝牙特征值变化
			notifyBLECharacteristicValueChange() {
				function buf2hex(buffer) {
					return Array.prototype.map.call(new Uint8Array(buffer), (x) => ('00' + x.toString(16)).slice(-2))
						.join('')
				}

				function stringToHex(str) {
					const arr = str.split('.')
					return arr
						.map((item) => {
							let num = Number(item).toString(16)
							if (num.length < 2) {
								num = '0' + num
							}
							return num
						})
						.join('')
				}
				// 监听通知
				var that = this;
				wx.onBLECharacteristicValueChange((res) => {
					console.log(res, '监听到返回的数据');
					wx.showToast({
						title: '监听到返回的数据',
						icon: 'none',
						duration: 800
					})
					that.isNotifyReturn = true;
					const hex = buf2hex(res.value)
					// const verify = `${stringToHex(device.lockId.split('.').reverse().join('.'))}0900005001`
					// const verifyCode = `${stringToHex(device.lockId.split('.').reverse().join('.'))}0900005000`
					let find = hex.indexOf('1a0794aa') > -1;
					if (find && (that.lock_brand)) {
						wx.showToast({
							title: '开锁成功',
							icon: 'none',
							duration: 800
						})
						// let key = data.data.data
						that.writeBLECharacteristicValueDelete(key)
						return
					}
				})

				if (this.lock_brand) {
					// var that = this;
					wx.notifyBLECharacteristicValueChange({
						deviceId: that.deviceId,
						serviceId: that.servicesUUID,
						characteristicId: that.notifyCharacteristicId,
						state: true,
						success: (res) => {
							// console.log('通知打开成功 231 锁,' + JSON.stringify(res));
						},
						fail: (res) => {
							// console.log('通知打开失败231 锁,' + JSON.stringify(res));
						}
					})
				}
				wx.notifyBLECharacteristicValueChange({
					deviceId: that.deviceId,
					serviceId: that.servicesUUID,
					characteristicId: that.notifyCharacteristicId,
					state: true,
					success: (res) => {
						// android 打开通知成功后等待200ms再写入数据，iOS不用等待
						if (that.isModel() == 'android') {
							setTimeout(() => {
								that.isNotifyReturn = false
								that.writeBLECharacteristicValue()
							}, that.delayTime)

						} else {
							wx.showToast({
								title: '苹果设备',
								icon: 'none',
								duration: 800
							})
							that.isNotifyReturn = false
							that.writeBLECharacteristicValue();
						}
					},
					fail: (res) => {
						console.log('通知打开失败', 4004)
						this.bluetoothFailAgain()
					},
				})
			},
			writeBLECharacteristicValueDelete(key) {
				// 火河A231门锁需要特殊处理
				let list = []
				while (key != null && key.length) {
					let str = key.substring(0, 2)
					let num = parseInt(str, 16)
					list.push(num)
					key = key.substring(2);
				}
				let arrayBuffer = new Uint8Array(list).buffer;
				console.log(arrayBuffer, 'arrayBuffer')
				// 向门锁写入删除数据
				wx.writeBLECharacteristicValue({
					deviceId: this.device.deviceId,
					serviceId: this.device.servicesUUID,
					characteristicId: this.writeCharacteristicId, //'0000FFF4-0000-1000-8000-00805F9B34FB',
					value: arrayBuffer,
					success: (res) => {
						console.log(res, 'res')
						// this.closeBluetoothAdapter()
					},
					fail: (res) => {
						console.log(res, 'res')
					},
				})
			},
			// 写入数据
			writeBLECharacteristicValue() {
				var that = this;
				let temp = `BABEC0DE` + that.blueYaCode;
				const secretNum = temp.toLocaleLowerCase();
				let buffer = '';
				console.log('往锁写入的数据：', secretNum)
				let step = 0
				let count = 0
				let step2 = 0

				function writeBLE() {
					console.log('次数' + count);
					buffer = that.stringToHexBuffer(secretNum)
					wx.writeBLECharacteristicValue({
						deviceId: that.deviceId,
						serviceId: that.servicesUUID,
						characteristicId: that.writeCharacteristicId,
						value: buffer,
						success: () => {
							if (that.lock_brand) {
								wx.showToast({
									title: '写入数据完成',
									icon: 'none',
									duration: 800
								})
								return
							}
							console.log(`锁写入数据剩余：${secretNum.length - step2}`)
							if (step2 != secretNum.length && !that.isNotifyReturn) {
								step += 32
								writeBLE();
							} else {
								// console.log('写入完成')
								wx.showToast({
									title: '写入数据完成',
									icon: 'none',
									duration: 800
								})
							}
						},
						fail: (res) => {
							count++
							// 写入失败时，重试3次，一次完整的写入，失败3次以上，算这次开锁失败
							if (count > 2 && !that.isNotifyReturn) {
								this.bluetoothFailAgain()
							} else if (!that.isNotifyReturn) {
								writeBLE()
							}
							console.log('写入数据失败', res)
						},
					})
				}
				writeBLE();
			},
			bluetoothFailAgain() {
				this.stopBluetoothDevicesDiscovery()
				this.closeBLEConnection()
				// 关闭蓝牙
				this.closeBluetoothAdapter(() => {
					this.failNums += 1
					console.log('失败次数:', this.failNums)
					if (this.failNums === this.maxFailNums) {
						console.log(`到失败次数上限:`, this.maxFailNums)
					} else if (this.failNums < this.maxFailNums) {
						setTimeout(() => {
							console.log('失败后重新开始')
							// 失败后的开始
							this.openLock(this.device)
						}, 200)
					}
				})
			},
			closeLock(id) {
				this.close(id)
			},
			open(item) {
				this.https('/room/openCharge', {
					room_id: item.id,
					// id: id,
				}).then(res => {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}).catch(err => {
					uni.showToast({
						title: err.msg,
						icon: 'none'
					})
				})
			},
			close(item) {
				const { activeStore: { id } } = this
				this.https('/room/closeCharge', {
					room_id: item.id,
					// roomId: item.id,
					storeId: id,
				}).then(res => {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}).catch(err => {
					uni.showToast({
						title: err.msg,
						icon: 'none'
					})
				})
			},
			// 开空调
			openKongtiao(id) {
				this.open(id)
			},
			// 关空调
			closeKongtiao(id) {
				this.close(id)
			},
			// 开插座
			openChazuo(item) {
				this.open(item)
				// const { activeStore: { id } } = this
				// this.https('/lock/open', {
				// 	type: 2,
				// 	storeId: id,
				// 	roomId: item.id,
				// 	userId: uni.getStorageSync('userinfo').id,
				// 	mobile: this.mobile
				// }, "GET").then(res => {
				// 	console.log(res, 'res');
				// 	uni.showToast({
				// 		title: res.msg,
				// 		duration: 2000
				// 	})
				// }).catch(error => {
				// 	uni.showToast({
				// 		title: error.msg,
				// 		duration: 2000
				// 	})
				// })
			},
			// 关插座
			closeChazuo(id) {
				this.close(id)
			},
			// 开灯
			openDong(id) {
				this.open(id)
			},
			// 关灯
			closeDong(id) {
				this.close(id)
			},
			isModel() {
				let res = wx.getSystemInfoSync();
				console.log(res.platform == 'ios', "苹果");
				console.log(res.platform == 'android', "安卓");
				console.log(res.platform == 'devtools', "模拟器");
				return res.res
			},
			// 关闭蓝牙
			stopBluetoothDevicesDiscovery() {
				wx.stopBluetoothDevicesDiscovery({
					complete: () => {
						this._discoveryStarted = false
					},
				})
			},
			// 断开
			closeBLEConnection() {
				if (this.deviceId) {
					wx.closeBLEConnection({
						deviceId: this.deviceId,
						success: () => {
							this.log('成功断开连接')
						},
					})
				}
			},
		}
	}
</script>

<style lang="scss">
	.box {
		display: flex;
		justify-content: flex-start;
		height: 500rpx;
		width: 100%;
		flex-wrap: wrap;
		margin-left: 19rpx;
	}

	.item {
		width: 670rpx;

		image {
			width: 72rpx;
			height: 72rpx;
		}

		.title {
			margin-bottom: 20rpx;
			font-size: 32rpx;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 500;
			color: #333333;
		}

		margin: 0 auto;
		margin-top: 40rpx;
	}

	.items {
		width: 200rpx;
		flex-wrap: wrap;
		height: 200rpx;
		background: #FFFFFF;
		box-shadow: 0px 0px 12rpx 0px rgba(189, 189, 189, 0.5);
		border-radius: 16rpx;
		display: flex;
		align-items: center;
		flex-direction: column;
		justify-content: space-around;
		font-size: 28rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 500;
		color: #333333;
		margin-right: 20rpx;

		.kongzhi {
			display: flex;
			justify-content: space-between;
			width: 100%;

			view {
				margin: 0 auto;
				width: 120rpx;
				background-color: #00809F;
				text-align: center;
				color: #FFFFFF;
				font-size: 20rpx;
				padding: 10rpx 0rpx;
				margin: 0 5rpx;
			}

			view:nth-child(1) {
				border-top-left-radius: 5rpx;
				border-bottom-left-radius: 5rpx;
				margin: 0 auto;
			}

			view:nth-child(2) {
				border-top-right-radius: 5rpx;
				border-bottom-right-radius: 5rpx;
			}

		}
	}
</style>